package com.tronsis.distribution.fragment.stock;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.lzy.imagepicker.bean.ImageItem;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.order.OrderDetailActivity;
import com.tronsis.distribution.bean.AskBuyBean;
import com.tronsis.distribution.bean.PayeeMethodBean;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.widget.ConfirmDialog;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 我的库存 fragment
 *
 * @author scofield@tronsis.com
 * @date 2019/3/13 15:58
 */
public class MyStockFragment extends BaseFragment {

    @BindView(R.id.rv_stock_un_pay)
    RecyclerView mRvUnPay;


    @BindView(R.id.srl)
    SwipeRefreshLayout mSrl;

    private List<AskBuyBean> mDataList = new ArrayList<>();
    private String mState;

    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;

    public static MyStockFragment create(String state) {
        Bundle bundle = new Bundle();
        bundle.putString("state", state);
        MyStockFragment fragment = new MyStockFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_my_stock_order, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected void initData() {
        initRv();
        Bundle bundle = getArguments();
        if (bundle != null) {
            mState = bundle.getString("state");
            httpGetList(mPage, mSize, true);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage message) {
        switch (message.getTag()) {
            case EventTag.MY_STOCK_ORDER_LIST:
                httpGetList(mPage = 1, mSize = 15, true);
                break;
            default:
                break;
        }
    }

    private void initRv() {
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);

        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                httpGetList(mPage = 1, mSize = 15, true);
            }
        });

        CommonAdapter<AskBuyBean> adapter = new CommonAdapter<AskBuyBean>(getContext(), mDataList, R.layout.item_my_stock_un_pay) {
            @Override
            protected void convert(final ViewHolder holder, final AskBuyBean askBuyBean, int position) {
                holder.setText(R.id.tv_order_num, askBuyBean.getCode());
                holder.setText(R.id.tv_time, DateUtil.getDateTimeString(askBuyBean.getStateOn()));

                //封面
//                holder.setImageByUrl(mContext, R.id.iv_cover, Url.FILE_DOWNLOAD + askBuyBean.getCouponCoverFid());
                if (!TextUtils.isEmpty(askBuyBean.getCouponCoverFid())) {
                    holder.setText(R.id.tv_count, "产品信息：");
                    holder.setVisible(R.id.iv_cover, true);
                    holder.setImageByUrl(mContext, R.id.iv_cover, Url.FILE_DOWNLOAD + askBuyBean.getCouponCoverFid());
                } else {
                    holder.setText(R.id.tv_count, getString(R.string.format_count, askBuyBean.getTotalItem()));
                    holder.setVisible(R.id.iv_cover, false);
                }


                RecyclerView rv = holder.getView(R.id.rv_pay_images);
                Button btnDelete = holder.getView(R.id.btn_delete);
                Button btnPay = holder.getView(R.id.btn_pay);

                if (StringUtil.isEquals(mState, StateUtil.MY_STOCK_ORDER_PAY)) {
                    holder.setVisible(R.id.ll_button, true);
                    holder.setVisible(R.id.tv_pay_way, false);
                } else {
                    holder.setVisible(R.id.ll_button, false);
                    String json = askBuyBean.getPayeeInfo();
                    PayeeMethodBean payeeBean = new Gson().fromJson(json, PayeeMethodBean.class);
                    if (payeeBean != null && payeeBean.getPayType() != null) {
                        holder.setVisible(R.id.tv_pay_way, true);

                        if (StringUtil.isEquals(payeeBean.getPayType(), "微信支付")) {
                            holder.setVisible(R.id.tv_label_pay_image, false);
                            holder.setText(R.id.tv_pay_way, "付款方式：在线支付");
                        } else {
                            holder.setVisible(R.id.tv_label_pay_image, true);
                            holder.setText(R.id.tv_pay_way, "付款方式：线下支付" );
                        }
                    } else {
                        holder.setVisible(R.id.tv_pay_way, true);
                        holder.setText(R.id.tv_pay_way, "付款方式：线下支付");
                    }

                    setImageRv(askBuyBean, rv);
                }

                btnDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDeleteDialog(holder.getLayoutPosition(), askBuyBean.getId());
                    }
                });

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, OrderDetailActivity.class);
                        intent.putExtra("AskBuyBean", askBuyBean);
                        intent.setType("my");
                        startActivity(intent);
                    }
                });
            }

            private void setImageRv(final AskBuyBean askBuyBean, RecyclerView rv) {
                CommonAdapter imageAdapter = new CommonAdapter<ImageItem>(mContext, CommonUtil.getSplitImage(askBuyBean.getPaymentFid()), R.layout.item_grid_image_view) {
                    @Override
                    protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                        holder.setImageByUrl(mContext, R.id.iv_item, imageItem.url);
                    }
                };
                rv.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });
                rv.setAdapter(imageAdapter);
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, OrderDetailActivity.class);
                intent.putExtra("AskBuyBean", mDataList.get(position));
                intent.setType("my");
                startActivity(intent);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mLoadMoreWrapper = new LoadMoreWrapper(adapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDataList.size() % 15 == 0 && mDataList.size() > 0 && mDataList.size() < mTotal) {
                    mPage = (mDataList.size() / 15) + 1;
                    httpGetList(mPage, mSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(getContext()).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(getContext(), MyDecoration.VERTICAL_LIST, height, color);
        mRvUnPay.addItemDecoration(decoration);
        mRvUnPay.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvUnPay.setAdapter(mLoadMoreWrapper);
    }

    private void showDeleteDialog(final int position, final String id) {
        ConfirmDialog dialog = new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {

            }

            @Override
            public void onRightButtonClick(View view) {
                httpDelete(position, id);

            }
        });
        dialog.showDialog("确认删除？", "取消", "确定");
    }

    private void httpGetList(int page, int size, final boolean isRefresh) {
        try {
            OrderBizFactory.createBiz().getMyBuyList(getActivity(), page, size, mState, new UICallBack() {
                @Override
                public void onStart() {
                    if (isRefresh) {
                        mSrl.setRefreshing(true);
                    }
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<AskBuyBean> list = listBean.getList();
                    if (isRefresh) {
                        mDataList.clear();
                        mDataList.addAll(list);
                    } else {
                        mDataList.addAll(list);
                    }
                    mLoadMoreWrapper.notifyDataSetChanged();

                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);

                }
            });
        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }

    private void httpDelete(final int position, String id) {
        try {
            OrderBizFactory.createBiz().deleteMyBuy(getActivity(), id, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    mLoadMoreWrapper.notifyItemRemoved(position);
                    mDataList.remove(position);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

}
